package com.zxy.ider.ehome;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.storage.StorageManager;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.ider.deskcust.DeskConstant;
import com.ider.deskcust.IDeskService;
import com.ider.deskcust.PageEntry;
import com.ider.deskcust.Theme;
import com.ider.deskcust.TileEntry;
import com.zxy.cust.DeskService;
import com.zxy.ider.ehome.View.FlyImageView;
import com.zxy.ider.ehome.View.TvGridView;
import com.zxy.ider.ehome.View.TvProgressBar;
import com.zxy.ider.ehome.adapter.TvhGridAdapter;
import com.zxy.ider.ehome.adapter.TvhGridAdapter2;
import com.zxy.ider.ehome.applist.AppListActivity;
import com.zxy.ider.ehome.bean.Application;
import com.zxy.ider.ehome.db.UpInfo;
import com.zxy.ider.ehome.util.ApplicationUtil;
import com.zxy.ider.ehome.util.NetUtil;
import com.zxy.ider.ehome.util.PreferenceManager;
import com.zxy.ider.ehome.util.SendInfo;
import com.zxy.ider.ehome.util.TvUtil;
import com.zxy.ider.ehome.util.WeatherUtil;
import com.zxy.ider.ehome.widget.MainUpView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HomeActivity extends Activity {
    public static final String TAG = "HomeActivity";
    public static IDeskService service;
//    private LetterSpacingTextView themename;
    private ImageView launcher_bg,launcher_logo,themename;
    private TileEntry[] tileEntrys,tileChildEntrys;
    private GridView homegrid,detilgrid;
    private TvGridView homegrid2;
    private static final long DEFAULT_TRAN_DUR_BIG_ANIM = 150;
    private static final long DEFAULT_TRAN_DUR_SMALL_ANIM = 50;
    private View lastSelected;
    private FlyImageView fly;
    private TextView weatherstatus;
    private WeatherUtil weatherUtil;
    private  AlertDialog dialog =null;
    private int gridwidth,gridheight;
    private boolean isUpdate = false;
    private PreferenceManager pmanager;
    private boolean isfirst = false;
    private ImageView netIcon,usbIcon,networkIcon,settingIcon,appsIcon;
    private int currentPage = 0;
    private String homeTitle;
    private Theme theme;
    private OkHttpClient okHttpClient;
    private int connectCount;
    private boolean dialogShow = false;
    private static List<UpInfo> upInfoList = new ArrayList<>();
    private TextClock mytextclock;
    private boolean firstIn;
    private static ConnectReceiver connectReceiver;
    private static boolean isRegisterReceivers = false;
    private static boolean isSendConnectBoad = false;
    private static int startConnectThread;
    private MainUpView mainUpView1;
    private View mOldView;
    private int mSelectPos = 0;
    final static private int[] LOG_DB =
            {KeyEvent.KEYCODE_6,KeyEvent.KEYCODE_5,KeyEvent.KEYCODE_4,
                    KeyEvent.KEYCODE_3,KeyEvent.KEYCODE_2,KeyEvent.KEYCODE_1
            };
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);


        firstIn =true;
        pmanager= PreferenceManager.getInstance(this);
        okHttpClient = new OkHttpClient.Builder().build();
//        connectCount = 0;
//        isConnect(this);
        if (connectReceiver==null) {
            connectReceiver = new ConnectReceiver();
        }
        bindMyService();
        registerReceivers();
        initViews();

        if (Build.VERSION.SDK_INT >=22) {
            isfirst = pmanager.isFirstRun();
            if (isfirst) {
                ActivityCompat.requestPermissions(HomeActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }

        //updateNetState(this);

        getUSBpath();
    }

    private void initViews() {

        homegrid2=(TvGridView)findViewById(R.id.homegrid2);
        mainUpView1 = (MainUpView) findViewById(R.id.mainUpView1);
        mainUpView1.setUpRectResource(R.drawable.cursoryellow);//white_light_10
        mainUpView1.setDrawUpRectPadding(new Rect(0, -140, 0, 140));

        themename = (ImageView) findViewById(R.id.theme_name);
        launcher_bg = (ImageView) findViewById(R.id.launcher_bg);
        launcher_logo = (ImageView) findViewById(R.id.launcher_logo);
//        fly = (FlyImageView) findViewById(R.id.mainUpView1);
        weatherstatus = (TextView) findViewById(R.id.weatherstatus);
        netIcon = (ImageView) findViewById(R.id.net_icon);
        usbIcon = (ImageView) findViewById(R.id.usb_icon);
        homegrid = (GridView) findViewById(R.id.homegrid);
        homegrid.setSelector(new ColorDrawable(0));
//        detilgrid = (TvHorizontalGridView) findViewById(R.id.detilGrid);
        Typeface tf=Typeface.createFromAsset(getAssets(), "right.otf");
        weatherstatus.setTypeface(tf);
        weatherUtil = new WeatherUtil(HomeActivity.this);
//        weatherUtil.getCity();
        networkIcon = (ImageView) findViewById(R.id.network_icon);
        settingIcon = (ImageView) findViewById(R.id.set_icon);
        appsIcon = (ImageView) findViewById(R.id.apps_icon);
        networkIcon.setOnFocusChangeListener(onfcus);
        settingIcon.setOnFocusChangeListener(onfcus);
        appsIcon.setOnFocusChangeListener(onfcus);
//        mytextclock = (TextClock) findViewById(R.id.myClock);

        initdata();
        setListener();
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    protected void onResume() {
//        if(is24Hour(HomeActivity.this)){
//            mytextclock.setFormat24Hour("yyyy年MM月dd日\nEEEE HH:mm");
//
//        }else{
//            mytextclock.setFormat12Hour("yyyy年MM月dd日\nEEEE h:mmaa");
//        }

        super.onResume();
        Log.d(TAG,"----onResume----");
        isConnect(this);
    }

    private boolean is24Hour(Context context){
        return DateFormat.is24HourFormat(context);
    }

    View.OnFocusChangeListener onfcus = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
                if(b){
                    mainUpView1.setVisibility(View.INVISIBLE);
                    if(homegrid2!=null) {
                        homegrid2.hiddenCursor(b);
                    }
                }else {
                    mainUpView1.setVisibility(View.VISIBLE);
                }
        }
    };



    private void initdata() {
        if(!NetUtil.isNetworkAvailable(HomeActivity.this)){
            Log.i(TAG, "initdata: start local data");
            String localdata = pmanager.getPackage("localData");
            if(localdata!=null){
                try {
                    JSONObject object = new JSONObject(localdata);
                    PageEntry page = new PageEntry(object);
                    theme = page.theme;
                    Glide.with(Appcontext.getAppContext()).load(theme.themelogo).error(R.mipmap.defaulterr).into(launcher_logo);
                    Glide.with(Appcontext.getAppContext()).load(theme.themebg).error(R.mipmap.wlcome).into(launcher_bg);
                    Glide.with(Appcontext.getAppContext()).load(theme.themetitle).into(themename);
                    homeTitle = theme.themetitle;
                    tileEntrys = page.tileEntrys;
                    Log.i(TAG, "onReceive: size=="+tileEntrys.length);

                    currentPage=0;
                    int size=tileEntrys.length;
                    if (size<9){
                        mainUpView1.setVisibility(View.GONE);
                        homegrid.setVisibility(View.GONE);
                        homegrid2.setVisibility(View.VISIBLE);
                        setCenterGrid(size,homegrid2);
                        homegrid2.setAdapter(new TvhGridAdapter2(tileEntrys));
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if(homegrid2.getChildAt(0)!=null){
                                    homegrid2.getChildAt(0).requestFocus();
                                }
                            }
                        },500);
                    }else {
					 homegrid2.setVisibility(View.GONE);
                        mainUpView1.setVisibility(View.VISIBLE);
                        homegrid.setVisibility(View.VISIBLE);                 
                        homegrid.setAdapter(new TvhGridAdapter(tileEntrys));
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (homegrid.getChildAt(0)!=null){
                                    setItemSelect(0,1.1f);
                                }
                            }
                        },500);
                    }
                    isUpdate= false;
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    private void bindMyService() {
        Intent in = new Intent();
        in.setAction(DeskConstant.DESK_SERVICE_ACTION);
        Intent intent = new Intent(this, DeskService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    ServiceConnection connection = new ServiceConnection() {


        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.i(TAG, "onServiceConnected: service connected !!!!!!!!!!!");
            service = IDeskService.Stub.asInterface(iBinder);
            String url = String.format(Constant.LAUNCHER_SERVER, NetUtil.getLocalEthernetMacAddress(), Constant.KEY_SERVER);
            try {
                if(NetUtil.isNetworkAvailable(Appcontext.getAppContext())) {
                    Log.d(TAG,"service.loadPages(url);");
                    service.loadPages(url);
                }else {
                    Log.d(TAG,"-----Constant.isConnect="+Constant.isConnect);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG,"---"+e.toString());
            }

        }


        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.i(TAG, "onServiceDisconnected: service ServiceDisconnected !!!!!!!!!!!");
            bindMyService();
        }
    };

    private void registerReceivers() {
        IntentFilter filter;
        filter = new IntentFilter();
        filter.addAction(DeskConstant.ACTION_UPDATE_PAGE_COUNT);
        registerReceiver(custreceiver, filter);
//        filter = new IntentFilter();
//        filter.addAction("com.ider.weather");
//        registerReceiver(weatheRecever, filter);
        filter = new IntentFilter();
        filter.addAction(NetUtil.CONNECTIVITY_CHANGE);
        filter.addAction(NetUtil.RSSI_CHANGE);
        filter.addAction(NetUtil.WIFI_STATE_CHANGE);
        registerReceiver(netReceiver, filter);
        filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_EJECT);
        filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addDataScheme("file");
        registerReceiver(mediaReciever, filter);
        filter = new IntentFilter();
        filter.addAction("com.ider.connected");
        registerReceiver(connectReceiver, filter);
        filter = new IntentFilter();
        filter.addAction("com.ider.disConnected");
        registerReceiver(disConnectReceiver, filter);

    }
    BroadcastReceiver disConnectReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("zxy", "disConnectReceiver onReceive");
            initdata();
//            showNetDialog();
            //netIcon.setImageResource(R.mipmap.eth_dis_off);
        }
    };
    class ConnectReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("zxy", "connectReceiver onReceive");
            Log.i("zxy", "NetUtil.isNetworkAvailable(Appcontext.getAppContext())"+NetUtil.isNetworkAvailable(Appcontext.getAppContext()));
            String action = intent.getAction();
            //Log.i("zxy", "action="+action);
            if(NetUtil.isNetworkAvailable(Appcontext.getAppContext())){
                if (NetUtil.isWifiConnect(context)) {
                    //netIcon.setImageResource(R.drawable.wifi_level);
                    //netIcon.setImageLevel(NetUtil.wifiLevel(context));
                } else {
                    Log.i("zxy", "R.mipmap.ethernet_off");
                    //netIcon.setImageResource(R.mipmap.ethernet_off);
                }
                if(dialog!=null){
                    dialog.cancel();
                    dialog.dismiss();
                }
                if (!Constant.isUpload) {
                    Constant.isUpload = true;
                    if (pmanager.getBoolean("isInfoSave")) {
                        uploadInfo();
                    }
                    Constant.isUpload = false;
                }
                //weatherUtil.getCity();
            }else{

//                showNetDialog();

                //netIcon.setImageResource(R.mipmap.eth_dis_off);
            }

            //networking
            try {
                String url = String.format(Constant.LAUNCHER_SERVER, NetUtil.getLocalEthernetMacAddress(), Constant.KEY_SERVER);
                if(service!=null&&NetUtil.isNetworkAvailable(Appcontext.getAppContext())&&!isUpdate) {
                    service.loadPages(url);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //updateNetState(context);

        }
    }

    private static synchronized void uploadInfo(){

           // Log.i("zxy", "isInfoSave");
//                        File file = new File(Constant.APK_CACHE_PATH,
//                                "backup.xml");
//                        if(file.exists()){
            //synchronized(upInfoList) {
                List<UpInfo> upInfos = DataSupport.findAll(UpInfo.class);
                Log.i("zxy", "upInfos.size()" + upInfos.size());
                if (upInfos.size() > 0) {

                    for (UpInfo upInfo : upInfos) {
                        if (!upInfoList.contains(upInfo)) {
                            upInfoList.add(upInfo);
                            SendInfo.upDataSupport(upInfo, upInfoList);
                        }
                    }

                }
           // }

    }

    BroadcastReceiver netReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //isConnect(context);
//            if (NetUtil.CONNECTIVITY_CHANGE.equals(action)) {
//                if(NetUtil.isNetworkAvailable(Appcontext.getAppContext())){
//                    if(dialog!=null){
//                        dialog.cancel();
//                        dialog.dismiss();
//                    }
//                    if(pmanager.getBoolean("isInfoSave")){
////                        File file = new File(Constant.APK_CACHE_PATH,
////                                "backup.xml");
////                        if(file.exists()){
//                        List<UpInfo> upInfos = DataSupport.findAll(UpInfo.class);
//                        Log.i("zxy", "upInfos.size()" +upInfos.size());
//                        if (upInfos.size()>0) {
//                            for (UpInfo upInfo:upInfos) {
//                                if (!upInfoList.contains(upInfo)){
//                                    upInfoList.add(upInfo);
//                                    SendInfo.upDataSupport(upInfo,upInfoList);
//                                }
//                            }
//                        }
//                    }
//                    weatherUtil.getCity();
//                }else{
//                    showNetDialog();
//                }
//
//                //networking
//                try {
//                    String url = String.format(Constant.LAUNCHER_SERVER, NetUtil.getLocalEthernetMacAddress(), Constant.KEY_SERVER);
//                    if(service!=null&&NetUtil.isNetworkAvailable(Appcontext.getAppContext())&&!isUpdate) {
//                        service.loadPages(url);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//                updateNetState(context);
//            }
        }
    };

    BroadcastReceiver mediaReciever = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            String data = intent.getDataString();
            if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
               //usbIcon.setVisibility(View.VISIBLE);
            }
            if (Intent.ACTION_MEDIA_UNMOUNTED.equals(action)) {

                //usbIcon.setVisibility(View.GONE);
            }
        }
    };
    BroadcastReceiver custreceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(DeskConstant.ACTION_UPDATE_PAGE_COUNT.equals(action)){
                boolean state = intent.getBooleanExtra(DeskConstant.PAGE_COUNT_STATE, false);
                Log.i(TAG, "onReceive: state="+state);
                if (state&&!isUpdate) {
                    String datanew = intent.getStringExtra(DeskConstant.PAGE_DETAIL_PAGES);
                    if(!TextUtils.isEmpty(datanew)){
                        pmanager.putString("localData",datanew);
                    }
                    PageEntry page = intent.getParcelableExtra(DeskConstant.PAGE_DETAIL_ENTRIES);
                    theme = page.theme;
                    Glide.with(Appcontext.getAppContext()).load(theme.themelogo).into(launcher_logo);
                    Glide.with(Appcontext.getAppContext()).load(theme.themebg).into(launcher_bg);
                    Glide.with(Appcontext.getAppContext()).load(theme.themetitle).into(themename);
                    homeTitle = theme.themetitle;
                    tileEntrys = page.tileEntrys;
                    if(tileEntrys!=null&&tileEntrys.length>0){
                    Log.i(TAG, "onReceive: size=="+tileEntrys.length);
                    Log.i(TAG, "initdata: color==="+theme.apptitlecolor);
                    currentPage=0;

                    int size=tileEntrys.length;
                        if (size<9){
                            mainUpView1.setVisibility(View.GONE);
                            homegrid.setVisibility(View.GONE);
                            homegrid2.setVisibility(View.VISIBLE);
                            setCenterGrid(size,homegrid2);
                            homegrid2.setAdapter(new TvhGridAdapter2(tileEntrys));
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if(homegrid2.getChildAt(0)!=null){
                                        homegrid2.getChildAt(0).requestFocus();
                                    }
                                }
                            },500);
                        }else {
                            homegrid2.setVisibility(View.GONE);
                            mainUpView1.setVisibility(View.VISIBLE);
                            homegrid.setVisibility(View.VISIBLE);
                            homegrid.setAdapter(new TvhGridAdapter(tileEntrys));
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if(homegrid.getChildAt(0)!=null){
                                        setItemSelect(0,1.1f);
                                    }
                                }
                            },500);
                        }
                    isUpdate= true;
                    }
                }
            }

        }
    };

    BroadcastReceiver weatheRecever = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
//            String data = intent.getStringExtra("weather");
//            weatherstatus.setText(data);
        }
    };
    @Override
    protected void onDestroy() {
        try{
            int a= 12;
            String x  =  String.valueOf(a);
            unregisterReceiver(custreceiver);
//            unregisterReceiver(weatheRecever);
            unregisterReceiver(netReceiver);
            unregisterReceiver(mediaReciever);
            unregisterReceiver(connectReceiver);
            unregisterReceiver(disConnectReceiver);
        }catch (Exception e){
            e.printStackTrace();
        }
        super.onDestroy();
    }




    /*设置GridView居中显示
    *
            * @param size
    *            元素个数
    */
    public void setCenterGrid(int size,TvGridView view) {
        int width = getWrapWidth(size)+10;
        int height = 0;
        if(size<=5){
            height= getResources().getDimensionPixelSize(R.dimen.px500);
            view.setRows(size);
            view.setPaddingLeft(getResources().getDimensionPixelOffset(R.dimen.px31));

            view.setSpaceHori(10);
        }else{
            int i =0;
            if(size%5==0){
                i=0;
            }else{
                i=1;
            }
            if(size<9){
                view.setRows(size / 2 + size % 2);
                if(size<7) {
                    view.setPaddingLeft(160);
                    view.setSpaceHori(200);
                }else if(size>=7&&size<9){
                    view.setPaddingLeft(70);
                    view.setSpaceHori(100);
                }
            }else{
                view.setRows(5);
                view.setPaddingLeft(getResources().getDimensionPixelOffset(R.dimen.px31));
                view.setSpaceHori(10);
            }
            height= getResources().getDimensionPixelSize(R.dimen.px500)*2;//(size/5+i);

        }
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                width+50,height);
        WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        int widthp = wm.getDefaultDisplay().getWidth();
        int heightp = wm.getDefaultDisplay().getHeight();
        if(size>5){
            params.topMargin=(heightp-height)/2+100;
        }else{
            params.topMargin=(heightp-height)/2;
        }

        params.leftMargin = (widthp-width)/2;
//                +getResources().getDimensionPixelSize(
//                R.dimen.px100);
        Log.i(TAG, "setCenterGrid: w=="+width+"*****h="+height);
        view.setLayoutParams(params);
    }


    public int getWrapWidth(int size) {

        int item_width = getResources().getDimensionPixelSize(
                R.dimen.px400);
        int horizontal_space = getResources().getDimensionPixelSize(
                R.dimen.px100);
        if (size == 1) {
            return item_width+50;
        } else if (size > 1 && size <= 5) {
            return item_width * size + horizontal_space * (size - 1);
        } else if (size > 5) {
            return getWrapWidth(5);
        }
        return 0;
    }

    void setItemSelect(int position, float scale) {
        if (homegrid.getChildCount() > 0) {
            homegrid.setSelection(position);
            mainUpView1.setFocusView(homegrid.getChildAt(position), scale);
            mOldView = homegrid.getChildAt(position);
        }
    }
    public void setListener(){

        homegrid.setOnHoverListener(new View.OnHoverListener() {
            @Override
            public boolean onHover(View view, MotionEvent motionEvent) {
                mainUpView1.setVisibility(View.INVISIBLE);
                return true;
            }
        });

        homegrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TileEntry tile=null;
                    if(currentPage==0) {
                        if (null!=tileEntrys&&tileEntrys.length>0)
                         tile = tileEntrys[i];
                    }else{
                        if (null!=tileChildEntrys&&tileChildEntrys.length>0)
                        tile = tileChildEntrys[i];
                    }
                    TvProgressBar progressBar = (TvProgressBar) view.findViewById(R.id.tpb_ring);
                    openItem(HomeActivity.this,progressBar,tile);
            }
        });

        homegrid.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                if (null!=view){
                    view.bringToFront();
                }
                mainUpView1.setFocusView(view, mOldView, 1.1f);
                mOldView = view;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });


            homegrid2.setOnItemClickListener2(new TvGridView.OnItemClickListener2() {
                @Override
                public void onItemClick(View item, int position) {
                    TileEntry tile=null;
                    if(currentPage==0) {
                         tile = tileEntrys[position];
                    }else{
                        tile = tileChildEntrys[position];
                    }
                    TvProgressBar progressBar = (TvProgressBar) item.findViewById(R.id.tpb_ring);
                    openItem(HomeActivity.this,progressBar,tile);
                }
            });

    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    public int getleftMargin(){
        WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int left = (width-gridwidth)/2;
        Log.i(TAG, "getleftMargin: left = "+left+"*****width="+width);
        return left;
    }

    public int getTopMargin(){
        WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        int height = wm.getDefaultDisplay().getHeight();
        int top = (height-gridheight)/2;
        return top;
    }

    public void showNetDialog(){
        if (dialog==null) {
            AlertDialog.Builder normalDialog =
                    new AlertDialog.Builder(HomeActivity.this);
            normalDialog.setTitle(getResources().getString(R.string.neterro_tip));
            normalDialog.setMessage("  " + getResources().getString(R.string.net_tip));
            normalDialog.setPositiveButton(getResources().getString(R.string.btn_enter),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent();
                            intent.setClassName("com.android.tv.settings", "com.android.tv.settings.connectivity.NetworkActivity");
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            HomeActivity.this.startActivity(intent);
                        }
                    });
            normalDialog.setNegativeButton(getResources().getString(R.string.Cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            dialog.dismiss();
                        }
                    });
            dialog = normalDialog.show();
        }else if (!dialog.isShowing()){
            dialog.show();
        }


    }


    public  void  openItem(Activity activity, TvProgressBar progress, TileEntry tile){
        Log.i(TAG, "openItem: ---------------"+tile.strutype);
        switch (tile.strutype){
            case "app":
                Log.i(TAG, "openItem: url =="+tile.apkaddress);
                Application app = ApplicationUtil.doApplication(Appcontext.getAppContext(),tile.strucommand);
                if(app==null) {

                    if (Build.VERSION.SDK_INT >=22) {
                        isfirst = pmanager.isFirstRun();
                        if (isfirst) {
                            ActivityCompat.requestPermissions(HomeActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                        }
                    } else {
                        File cacheFolder = new File(Constant.APK_CACHE_PATH);
                        if (!cacheFolder.exists()) {
                            Log.i(TAG, "openItem: file not exit");
                            boolean s1 = cacheFolder.mkdirs();
                            Log.i(TAG, "openItem: file =" + cacheFolder.exists() + s1);
                        }
                    }
                    if(NetUtil.isNetworkAvailable(HomeActivity.this)) {
                        if(!progress.isDownloading()){
                            showUpdateDialog(activity, tile.apkaddress, progress);
                        }
                    }else{
                        //showNetDialog();
                    }
                }else{
                    app.setApppara(tile.apppara);
                    ApplicationUtil.startApp(Appcontext.getAppContext(),app);
                }
                break;
            case "web":
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                String url = tile.strucommand;
                if (tile.strucommand_web_para_ismac.equals("1")){
                    url = url+"mac="+NetUtil.getLocalEthernetMacAddress();
                }
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                Log.d(TAG,"===openItem web url==="+url);
                Log.d(TAG,"===openItem web content_url==="+content_url);
                try{
                    startActivity(intent);
                }catch (Exception e){
                    Log.d(TAG,"===openItem web==="+e.toString());
                    TvUtil.showToast(this,"无法打开网页");
                }

                String startTime = System.currentTimeMillis()+"";
                UpInfo upInfo = new UpInfo(Constant.mac, Build.MODEL,url,startTime);
                if(NetUtil.isNetworkAvailable(HomeActivity.this)){
                    SendInfo.upInfo(upInfo,HomeActivity.this);
                }else{
                    upInfo.save();
                    pmanager.putBoolean("isInfoSave",true);
                    Log.i("zxy", "upInfo.save()=" +upInfo.getAllInfo());
//              pm.putBoolean("isUpload",false);
                }
                break;
            case "interface":
                OpenInterface(tile);
                //GetandSaveCurrentImage(tile.stru);
                break;
            case "local":
                Intent intentFile = new Intent(HomeActivity.this, FileActivity.class);
                String path = "/mnt/sata/"+tile.strucommand;//Environment.getExternalStorageDirectory()+"/"+tile.strucommand;
                File file = new File(path);
                    if(!file.exists()){
                            file.mkdir();
                    }
                    intentFile.putExtra("dataUrl", path);
                    intentFile.putExtra("title", tile.strucommand);
                intentFile.putExtra("logoAddress",theme.playlogo);
                    startActivity(intentFile);

                break;
        }
        Log.i(TAG,"tile.strubg="+tile.strubg);
        if (!tile.strubg.equals("")) {
            Glide.with(Appcontext.getAppContext()).load(tile.strubg).into(launcher_bg);
        }
    }

    public void OpenInterface(TileEntry tile){
        try {
            JSONArray jarray = new JSONArray(tile.stru);
            tileChildEntrys = new TileEntry[jarray.length()];
            for(int i = 0;i<jarray.length();i++){
                tileChildEntrys[i]=new TileEntry(jarray.getJSONObject(i));
            }
        } catch (JSONException e) {
            tileChildEntrys= new TileEntry[0];
            e.printStackTrace();
        }
        if(tileChildEntrys!=null) {
            int size=tileChildEntrys.length;
            if (size > 0) {
                if (size<9){
                    mainUpView1.setVisibility(View.GONE);
                    homegrid.setVisibility(View.GONE);
                    homegrid2.setVisibility(View.VISIBLE);
                    homegrid2.removeAllViews();
                    setCenterGrid(size,homegrid2);
                    homegrid2.setAdapter(new TvhGridAdapter2(tileChildEntrys));
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(homegrid2.getChildAt(0)!=null){
                                homegrid2.getChildAt(0).requestFocus();
                            }
                        }
                    },500);
                }else {
                    mainUpView1.setVisibility(View.VISIBLE);
                    homegrid.setVisibility(View.VISIBLE);
                    homegrid2.setVisibility(View.GONE);
                    homegrid.setAdapter(new TvhGridAdapter(tileChildEntrys));
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(homegrid.getChildAt(0)!=null){
                                setItemSelect(0,1.1f);
                            }
                        }
                    },500);
                }
                Glide.with(Appcontext.getAppContext()).load(tile.strutitle).into(themename);
            }
            currentPage = 1;
        }
    }
    private int mKeycodeStackIndex = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK||keyCode==KeyEvent.KEYCODE_HOME){
            if(currentPage!=0) {
                Glide.with(Appcontext.getAppContext()).load(homeTitle).into(themename);

                int size=tileEntrys.length;
                if (size<9){
                    mainUpView1.setVisibility(View.GONE);
                    homegrid.setVisibility(View.GONE);
                    homegrid2.setVisibility(View.VISIBLE);
                    homegrid2.removeAllViews();
                    setCenterGrid(tileEntrys.length, homegrid2);
                    homegrid2.setAdapter(new TvhGridAdapter2(tileEntrys));
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(homegrid2.getChildAt(0)!=null){
                                homegrid2.getChildAt(0).requestFocus();
                            }
                        }
                    },500);
                }else {
                    mainUpView1.setVisibility(View.VISIBLE);
                    homegrid2.setVisibility(View.GONE);
                    homegrid.setVisibility(View.VISIBLE);
                    homegrid.setAdapter(new TvhGridAdapter(tileEntrys));
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(homegrid.getChildAt(0)!=null){
                                setItemSelect(0,1.1f);
                            }
                        }
                    },500);
                }
//                homegrid.removeAllViews();
//                setCenterGrid(tileEntrys.length, homegrid);
//                homegrid.setAdapter(new TvhGridAdapter(tileEntrys));
//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        if(homegrid.getChildAt(0)!=null){
//                            homegrid.getChildAt(0).requestFocus();
//                        }
//                    }
//                },500);
                currentPage = 0;
                Glide.with(Appcontext.getAppContext()).load(theme.themebg).into(launcher_bg);
            }

            return true;
        }
        if (keyCode == LOG_DB[mKeycodeStackIndex])
        {
            Log.i(TAG, "onKeyDown: mKeycodeStackIndex++"+mKeycodeStackIndex);
            mKeycodeStackIndex++;

        }
        else{
            mKeycodeStackIndex = 0;
        }
        if (mKeycodeStackIndex >= LOG_DB.length){
            mKeycodeStackIndex=0;
            Intent intent = new Intent(HomeActivity.this, WebActivity.class);
            startActivity(intent);
            return true;
        }
//        if(keyCode==KeyEvent.KEYCODE_0){
//            Intent intent = new Intent(HomeActivity.this, WebActivity.class);
//            startActivity(intent);
//        }
        return super.onKeyDown(keyCode, event);
    }

    public static Bitmap move;
    public static Bitmap keep;
    public void GetandSaveCurrentImage(String json) {

        // 获取屏幕
        View decorview = getWindow().getDecorView();
        int keepPosition = 720 / 2 + Constant.commonAppTranLength / 2;
        decorview.setDrawingCacheEnabled(true);
        decorview.buildDrawingCache();
        Bitmap Bmp = Bitmap.createBitmap(decorview.getDrawingCache());
        decorview.destroyDrawingCache();

        if (move != null && !move.isRecycled()) {
            move.recycle();
            move = null;
        }
        if (keep != null && !keep.isRecycled()) {
            keep.recycle();
            keep = null;
        }

        if (Bmp != null && !Bmp.isRecycled()) {
            move = Bitmap.createBitmap(Bmp, 0, 0, Bmp.getWidth(), keepPosition);
            keep = Bitmap.createBitmap(Bmp, 0, keepPosition, Bmp.getWidth(),
                    Bmp.getHeight() - keepPosition);
        }
        Intent intent = new Intent(HomeActivity.this, CommonApp.class);
        intent.putExtra("keep", keepPosition);
        intent.putExtra("json",json);
        startActivity(intent);

    }

    @SuppressLint("SdCardPath")
    public void showUpdateDialog(final Activity activity, final String url, final TvProgressBar progress){
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(activity);
        normalDialog.setIcon(R.mipmap.ic_launcher);
        normalDialog.setTitle(activity.getResources().getString(R.string.downappTitle));
        normalDialog.setMessage("          MESSAGE:     "+activity.getResources().getString(R.string.downapp));
        normalDialog.setPositiveButton(activity.getResources().getString(R.string.btn_enter),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        Log.i(TAG, "onClick: url =="+url);

                        startDownload(Constant.APK_CACHE_PATH,url,activity,progress);
                        Toast.makeText(activity, "开始下载", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                        dialog.cancel();
                    }
                });
        normalDialog.setNegativeButton(activity.getResources().getString(R.string.Cancel),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        dialog.dismiss();
                        dialog.cancel();
                    }
                });
        normalDialog.show();

    }

    public void startDownload(final String path, String url, final Activity activity, final TvProgressBar loadingbar){
        loadingbar.setVisibility(View.VISIBLE);
        RequestParams requestParams = new RequestParams(url);
        requestParams.setSaveFilePath(path+"/"+NetUtil.getNameFromUrl(url));
        x.http().get(requestParams, new Callback.ProgressCallback<File>() {

            @Override
            public void onCancelled(CancelledException arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onError(Throwable arg0, boolean arg1) {
                // TODO Auto-generated method stub
                Toast.makeText(activity, "下载失败，请检查网络和SD卡", Toast.LENGTH_SHORT).show();
                loadingbar.setDownloading(false);
            }

            @Override
            public void onFinished() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onSuccess(File file) {
                // TODO Auto-generated method stub
                Toast.makeText(activity, "下载成功,开始安装", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Intent.ACTION_VIEW);
                Log.i(TAG, "onSuccess: file=="+file.getAbsolutePath());
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                activity.startActivity(intent);
                //InstallUtil.installSlient(LAUNCHER_INSTALL_PATCH);
                loadingbar.setVisibility(View.GONE);
                loadingbar.setDownloading(false);
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                int progress = (int) (current*100/total);
                Log.i(TAG, "onLoading: progress="+progress);
                loadingbar.setProgress(progress);
                loadingbar.setDownloading(true);
            }

            @Override
            public void onStarted() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onWaiting() {
                // TODO Auto-generated method stub

            }

        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        boolean writeAccepted = false;
        switch (requestCode) {
            case 1:
                String state = Environment.getExternalStorageState();
                    Log.i(TAG, "onRequestPermissionsResult: state="+state);
                if (Environment.MEDIA_MOUNTED.equals(state)) {
                    pmanager.setFirstRun(false);
                    File cacheFolder = new File(Constant.APK_CACHE_PATH);
                    if (!cacheFolder.exists()) {
                        Log.i(TAG, "openItem: file not exit");
                        boolean s1 = cacheFolder.mkdirs();
                        Log.i(TAG, "openItem: file ="+cacheFolder.exists()+s1);
                    }
                }
                break;
        }
    }

    public void updateNetState(final Context context) {
        if (NetUtil.isNetworkAvailable(context)) {
            connectCount = 0;
            //isConnect(context);
        } else {
            netIcon.setImageResource(R.mipmap.eth_dis_off);
        }
    }
    private void startConnectThread1(final Context context){
        new Thread() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder()
                            .url("http://mp.encm.com.cn/Interface/connect").build();
                    Call call = okHttpClient.newCall(request);
                    Response response = call.execute();
                    String result = response.body().string();
                    //Log.i("result1",result+"startConnectThread="+Constant.startConnectThread);
                    if (result.equals("{\"result\":\"1\"}")){
                        Constant.isConnect = true;
                        if (!isSendConnectBoad) {
                            isSendConnectBoad = true;
                            Log.i("result", "com.ider.connected");
                            Intent intent = new Intent("com.ider.connected");
                            context.sendBroadcast(intent);
                        }

                    }else {
                        Constant.isConnect = false;
                        if (isSendConnectBoad||firstIn) {
                            isSendConnectBoad = false;
                            firstIn = false;
                            Intent intent =new Intent("com.ider.disConnected");
                            context.sendBroadcast(intent);

                        }
                    }
                    if (Constant.startConnectThread==1){
                        sleep(2000);
                        startConnectThread1(context);
                    }
                } catch (Exception e) {
                    Log.d(TAG,"Thread1----"+e.toString());
                    Constant.isConnect = false;
                    if (isSendConnectBoad||firstIn) {
                        isSendConnectBoad = false;
                        firstIn = false;
                        Intent intent =new Intent("com.ider.disConnected");
                        context.sendBroadcast(intent);

                    }
                    if (Constant.startConnectThread==1){
                        try {
                            sleep(2000);
                        } catch (InterruptedException e1) {
                            //e1.printStackTrace();
                        }
                        startConnectThread1(context);
                    }
                    //Log.i("result1","Exception e"+"startConnectThread="+Constant.startConnectThread);
                    //e.printStackTrace();
                }
            }
        }.start();
    }
    private void startConnectThread2(final Context context){
        new Thread() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder()
                            .url("http://mp.encm.com.cn/Interface/connect").build();
                    Call call = okHttpClient.newCall(request);
                    Response response = call.execute();
                    String result = response.body().string();
                    //Log.i("result2",result+"startConnectThread="+Constant.startConnectThread);
                    if (result.equals("{\"result\":\"1\"}")){
                        Constant.isConnect = true;
                        Log.d(TAG,"result="+result);
                        Log.d(TAG,"isSendConnectBoad="+isSendConnectBoad);
                        if (!isSendConnectBoad) {
                            isSendConnectBoad = true;
                            Log.i("result", "com.ider.connected");
                            Intent intent = new Intent("com.ider.connected");
                            context.sendBroadcast(intent);

                        }

                    }else {
                        Constant.isConnect = false;
                        Log.d(TAG,"result="+result);
                        Log.d(TAG,"isSendConnectBoad="+isSendConnectBoad);
                        Log.d(TAG,"firstIn="+firstIn);
                        if (isSendConnectBoad||firstIn) {

                            isSendConnectBoad = false;
                            firstIn = false;
                            Intent intent =new Intent("com.ider.disConnected");
                            context.sendBroadcast(intent);

                        }
                    }
                    if (Constant.startConnectThread==2){
                        Log.d(TAG,"reStartThread2");
                        sleep(2000);
                        startConnectThread2(context);
                    }
                } catch (Exception e) {
                    Log.d(TAG,"Thread2----"+e.toString());
                    Constant.isConnect = false;
                    if (isSendConnectBoad||firstIn) {
                        isSendConnectBoad = false;
                        firstIn = false;
                        Intent intent =new Intent("com.ider.disConnected");
                        context.sendBroadcast(intent);

                    }
                    if (Constant.startConnectThread==2){
                        try {
                            sleep(2000);
                        } catch (InterruptedException e1) {
                            //e1.printStackTrace();
                        }
                        startConnectThread2(context);
                        Log.d(TAG,"Exception startConnectThread = "+startConnectThread);
                    }
                    //Log.i("result2","Exception e"+"startConnectThread="+Constant.startConnectThread);
                    //e.printStackTrace();
                }
            }
        }.start();
    }
    private void isConnect(final Context context){
        if (Constant.startConnectThread ==1){
            Log.d(TAG,"startConnectThread = "+startConnectThread);
            Constant.startConnectThread = 2;
            startConnectThread2(context);
        }else {
            Log.d(TAG,"startConnectThread = "+startConnectThread);
            Constant.startConnectThread = 1;
            startConnectThread1(context);

        }
    }


    public void IconOnclick(View view){
        switch (view.getId()){
            case R.id.network_icon:
                Intent intent = new Intent();
                intent.setClassName("com.android.tv.settings","com.android.tv.settings.connectivity.NetworkActivity");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
            case R.id.set_icon:
                Intent intent2 = new Intent();
                ComponentName cm2 = new ComponentName("com.android.settings","com.android.settings.Settings");
                intent2.setComponent(cm2);
                startActivity(intent2);
                break;
            case R.id.apps_icon:
                Intent intent3 = new Intent(HomeActivity.this,AppListActivity.class);
                startActivity(intent3);
                break;
        }
    }

   public void getUSBpath(){
       File f = new File("/mnt/sata");
       Log.i(TAG, "getUSBpath: f="+f.exists());
//      String [] pa =  getNUSBPath();
//       Log.i(TAG, "getUSBpath: pa0="+pa[0]+"pa1="+pa[1]+"pa2="+pa[2]);
   }

    private String[] getNUSBPath() {
        String[] paths = new String[3];
        StorageManager storageManager = (StorageManager) getSystemService(Service.STORAGE_SERVICE);
        try {
            Class SM = Class.forName("android.os.storage.StorageManager");
            Class VI = Class.forName("android.os.storage.VolumeInfo");
            Class DI = Class.forName("android.os.storage.DiskInfo");
            Method getVolumes = SM.getDeclaredMethod("getVolumes");
            Method getPath = VI.getDeclaredMethod("getPath");
            Method getDiskInfo = VI.getDeclaredMethod("getDisk");
            Method isMountedReadable = VI.getDeclaredMethod("isMountedReadable");
            Method getType = VI.getDeclaredMethod("getType");

            Method isUsb = DI.getDeclaredMethod("isUsb");
            Method isSd = DI.getDeclaredMethod("isSd");
            List volumeInfos = (List) getVolumes.invoke(storageManager);
            for(int i = 0; i < volumeInfos.size(); i++) {
                Object volume = volumeInfos.get(i);
                if(volume != null && (boolean)isMountedReadable.invoke(volume) && (Integer) getType.invoke(volume) == 0) {
                    File path = (File) getPath.invoke(volumeInfos.get(i));
                    Log.i("tag", "path = " + path.getAbsolutePath());
                    Object diskInfo = getDiskInfo.invoke(volumeInfos.get(i));
                    boolean isUSB = (boolean) isUsb.invoke(diskInfo);
                    boolean isSD = (boolean) isSd.invoke(diskInfo);
                    if(isUSB) {
                        if(paths[0] == null) {
                            paths[0] = path.getAbsolutePath();
                        } else {
                            paths[1] = path.getAbsolutePath();
                        }
                    }
                    if(isSD) {
                        paths[2] = path.getAbsolutePath();
                    }
                }

            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return paths;
    }
}
